import axios from 'axios';
import { useEditorStore } from '@/store/editor'

// 创建axios实例
const instance = axios.create({
    baseURL: '', // 已在vue.config.js中配置代理
    timeout: 5000, // 请求超时时间
    headers: {
        'Content-Type': 'application/json'
    }
});

// 请求拦截器
instance.interceptors.request.use(
    config => {
        const noTokenUrls = ['/sign_in', '/sign_up'];
        // 添加更详细的日志
        console.log('Request interceptor - URL:', config.url);
        console.log('Request interceptor - Method:', config.method);
        console.log('Request interceptor - Time:', new Date().toISOString());

        if (!noTokenUrls.includes(config.url)) {
            const store = useEditorStore();
            const token = store.getUserToken;
            console.log('Token status for request:', {
                url: config.url,
                hasToken: !!token,
                tokenLength: token ? token.length : 0
            });

            if (!token) {
                console.warn('No token available for request:', config.url);
                // 不在这里处理路由，而是抛出错误
                return Promise.reject(new Error('No authentication token found'));
            }
            // 确保 token 格式正确
            config.headers.Authorization = token.startsWith('Bearer ') ? token : `Bearer ${token}`;
            console.log('Request headers:', config.headers);
        }
        return config;
    },
    error => {
        console.error('Request interceptor error:', error);
        return Promise.reject(error);
    }
);

// 响应拦截器
instance.interceptors.response.use(
    response => {
        // 对响应数据做点什么
        return response;
    },
    error => {
        // 对响应错误做点什么
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    // 未授权，跳转到登录页
                    console.error('Unauthorized, please login');
                    // 清除用户认证信息
                    localStorage.removeItem('token');
                    localStorage.removeItem('userEmail');
                    window.location.href = '/';
                    break;
                case 404:
                    console.error('API not found');
                    break;
                case 500:
                    console.error('Server error');
                    break;
                default:
                    console.error(`Error: ${error.message}`);
            }
        } else {
            console.error('Network error:', error.message);
        }
        return Promise.reject(error);
    }
);

export default instance;
